<template>
    <div>
        <div v-if="isCanRecommend" class="white-bg bottom-shadow margin-top12 padding43" style="margin:12px auto">
            <div style="padding:20px 0">
                <div  class="recommend-btn" @click="openModal">{{$t('recommend_to_subordinates')}}</div>
            </div>
        </div>
        <van-popup v-model="isShow" style="width: 100%;height:100vh;">
            <div class="popup1">
                <div>
                    <div>
                        <div>
                            <form action="/">
                                <van-search
                                    v-model="searchData.searchContent"
                                    :placeholder="$t('subordinate_search_tip')"
                                    input-align="left"
                                    @search="getSearch"
                                />
                            </form>
                        </div>
                    </div>
                    <div class="content-box">
                    <div class="c-title" style="color:#666">
                        {{$t('subordinate_search_result')}} <span style="color:#999">({{total}})</span>
                        <div class="add-all" :disabled="allBtnDisabled" @click="addMany(false)">{{$t('add')}}{{$t('type_all_title')}}</div>
                    </div>
                        <div v-if="commonData && commonData.length > 0" class="list">
                            <div>
                                <ul>
                                    <li class="clearfix" v-for="(item, i) in commonData" :key="i" :class="{'no-border': i === commonData.length - 1}">
                                        <div class="left clearfix">
                                            <div class="avatar">
                                                <img class="user-img" v-if="item.userPoto" :src="item.userPoto"/>
                                            </div>
                                            <div class="txt">
                                                <div class="txt-p">
                                                    <span class="txt-area">{{item.usrDisplayBil}}</span>
                                                    <span class="txt-area"><span>{{item.usgDisplayBil}}</span></span>
                                                    <span class="txt-area">{{item.ugrDisplayBil}}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="right">
                                            <van-button class="min-sm-bt add-btn" @click.native="addOnly(item)" :disabled="item.ifSignUp">{{item.ifSignUp ? $t('added'): $t('add')}}</van-button>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                    </div>
                    <!--暂无数据-->
                    <div v-if="!isLoading && total === 0" style="height:100%;">
                        <div class="box-table" style="width:100%;height:100%;padding:20px 0">
                            <div class="box-table-cell" style="text-align: center;">
                                <div class="no-data">
                                    <img src="/static/images/no-data.png" alt=""/>
                                    <p class="color999">{{ $t("no_data") }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    </div>
                </div>
                </div>
                <common-loading :isLoading="recommendLoading"></common-loading>
                <div class="dialog-footer" style="margin-bottom:20px;margin-top:20px;">
                    <div class="btn-box clearfix" v-if="commonData && commonData.length > 0">
                        <div :class="{'disabled': reqParams.pageNo === 1}" class="page-btn" @click="changePage('prev')">{{$t('prev')}}</div>
                        <span style="line-height:32px">{{reqParams.pageNo}}/{{totalPage }}</span>
                        <div :class="{'disabled': reqParams.pageNo === totalPage}" class="page-btn" @click="changePage('next')">{{$t('next')}}</div>
                    </div>
                    <div class="cancel-btn">
                        <van-button plain type="default" @click.native="cancel">{{$t('cancel')}}</van-button>
                    </div>
                </div>
            </van-popup>
            <van-dialog v-model="showErr" :title="$t('modal_title_notice')">
                <div>
                    <div style="margin-bottom:5px;" v-for="(err, ind) in errorList" :key="ind">
                        <h3>{{$t(err.errStatus)}}:</h3>
                        <div><span style="margin-right:5px;" v-for="(user, i) in err.userList" :key="i">{{user.usrDisplayBil ? user.usrDisplayBil : '--'}}(id: {{user.usrEntId}})<span v-if="i < err.userList.length - 1">、</span></span></div>
                    </div>
                </div>
            </van-dialog>
    </div>
</template>
<script>
import {Dialog, Search, Popup} from 'vant';
import CommonLoading from '@/components/common/loading';
export default {
    name: 'recommend-btn',
    components: {
        vanPopup: Popup,
        [Search.name]: Search,
        CommonLoading,
        'van-dialog': Dialog.Component
    },
    props: {
        itmId: {
            type: String, // 課程id
            default: '0'
        }
    },
    data() {
        return {
            recommendLoading: false,
            showErr: true, // 报错提醒框开启、关闭
            errorList: [], // 批量添加报错集合
            onFetching: false, //滚动到底部
            isTop: false,
            isLoading: false,
            isCanRecommend: false,
            isShow: false,
            commonData: [],
            loading: false,
            total: 0,
            totalPage: 0,
            tab: 'all',
            searchData: {
                searchContent: ''
            },
            reqParams: {
                pageNo: 1,
                pageSize: 12,
                sortname: '',
                sortorder: 'DESC'
            },
            usrEntIdList: [],
            allBtnDisabled: true
        };
    },
    methods: {
        openModal() {
            this.isShow = true;
            this.getSubList();
        },
        /**
         * @description: 搜索
         * @param {*}
         * @return {*}
         */
        getSearch() {
            this.reqParams.pageNo = 1;
            this.getSubList();
        },
        cancel() {
            this.isShow = false;
            // 恢复初始化数据
            this.searchData = {
                searchContent: ''
            };
            this.reqParams = {
                pageNo: 1,
                pageSize: 12,
                sortname: '',
                sortorder: 'DESC'
            };
            this.commonData = [];
            this.total = 0;
            this.totalPage = 0;
            this.getSubordinateCount();
        },
        async getSubList() {
            this.allBtnDisabled = true;
            this.commonData = [];
            this.recommendLoading = true;
            this.$axios({
                method: 'POST',
                url: '/app/api/trainee/course/subordinate/list',
                params: this.reqParams,
                data: {
                    searchContent: this.searchData.searchContent,
                    itmId: this.itmId
                }
            }).then(res => {
                if (res.data) {
                    this.commonData = res.data.results;
                    this.total = res.data.totalRecord;
                    this.totalPage = res.data.totalPage;
                    this.isShow = true;
                    this.onFetching = false;
                    this.isTop = true;
                    this.recommendLoading = false;
                    if (this.commonData) {
                        var addList = [];
                        this.commonData.forEach(item => {
                            if (!item.ifSignUp) {
                                addList.push(item.userEntId);
                            }
                        });
                        if (addList.length > 0) {
                            this.allBtnDisabled = false;
                        }
                    }
                }
            });
            this.loading = false;
        },
        /**
         * 改变页码
         * */
        changePage(type) {
            if (type === 'prev') {
                if (this.reqParams.pageNo === 1) {
                    return;
                }
                this.reqParams.pageNo -= 1;
                this.getSubList();
            } else if (type === 'next') {
                if (this.reqParams.pageNo === this.totalPage) {
                    return;
                }
                this.reqParams.pageNo += 1;
                this.getSubList();
            }
        },
        // 点击添加按钮（单一用户）
        addOnly(item) {
            if (item.ifSignUp) {
                return;
            }
            this.usrEntIdList = [];
            this.usrEntIdList[0] = item.userEntId;
            this.postRecommend();
        },
        // 点击添加按钮（添加当前页全部）
        addMany(sure) {
            var addList = [];
            this.commonData.forEach(item => {
                if (!item.ifSignUp) {
                    addList.push(item.userEntId);
                }
            });
            if (addList.length <= 0) {
                return false;
            }
            if (!sure) {
                Dialog.confirm({
                    width: '180px',
                    confirmButtonText: this.$t('mall_10'),
                    confirmButtonColor: '#00aeef',
                    message: this.$t('is_sure') + '?'
                }).then(() => {
                    // on confirm
                    this.addMany(true);
                }).catch(() => {
                    return false;
                }); ;
            } else {
                this.usrEntIdList = addList;
                this.postRecommend();
            };
        },
        /**
         * @description: 推荐给下属 - 报名事件
         * @param {*}
         * @return {*}
         */
        postRecommend() {
            if (!this.itmId) {
                return;
            }
            const obj = {
                itmId: Number(this.itmId),
                usrEntIdList: this.usrEntIdList
            };
            this.recommendLoading = true;
            this.$axios({
                method: 'POST',
                url: '/app/api/trainee/course/aeInsMultiAppn',
                data: obj
            }).then(res => {
                if (res.data) {
                    this.getSubList();
                    this.recommendLoading = false;
                    Dialog.alert({
                        width: '180px',
                        confirmButtonText: this.$t('mall_10'),
                        confirmButtonColor: '#00aeef',
                        message: this.$t('recommend_success')
                    });
                }
            }).catch((error) => {
                if (error.response) {
                    let err = error.response.data;
                    if (err.status === 'ERROR') {
                        let errStatus = [];
                        let errMsg = [];
                        err.resultVOList.forEach(res => {
                            let user = {
                                usrDisplayBil: res.usrDisplayBil,
                                usrEntId: res.usrEntId
                            };
                            if (!errStatus.includes(res.appErrMsg)) {
                                errStatus.push(res.appErrMsg);
                                let arr = {
                                    errStatus: res.appErrMsg,
                                    userList: []
                                };
                                arr.userList.push(user);
                                errMsg.push(arr);
                            } else {
                                const index = errStatus.indexOf(res.appErrMsg);
                                errMsg[index].userList.push(user);
                            }
                        });
                        this.errorList = errMsg;
                        this.getSubList();
                        this.recommendLoading = false;
                        this.showErr = true;
                    } else {
                        Dialog.alert({
                            width: '180px',
                            confirmButtonText: this.$t('mall_10'),
                            confirmButtonColor: '#00aeef',
                            message: this.$t(err.errMsg)
                        });
                        this.recommendLoading = false;
                    }
                }
            });
        },
        /**
         * 进入访客模式
         * */
        goVisitor(id) {
            const data = {
                userId: id
            };
            this.goPage({ path: '/visitor', query: data });
        },
        getSubordinateCount() {
            this.$axios({
                method: 'POST',
                url: '/app/api/trainee/my/subordinate/count'
            }).then(res => {
                if (res.data) {
                    if (res.data > 0) {
                        this.isCanRecommend = true;
                    } else {
                        this.isCanRecommend = false;
                    }
                }
            });
        }
    },
    mounted() {
        this.getSubordinateCount();
    }
};
</script>
<style scoped lang="less">
.add-all{
    position: absolute;
    top: 20px;
    right: 20px;
    color:#075ebb;
}
.recommend-btn{
    margin: 0 auto;
    width: 186px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    background: #075ebb;
    color: #ffffff;
    border-radius: 4px;
    f
    &.cur{
        background: #E6E6E6;
        color: #cccccc;
    }
}

.min-sm-bt{
    min-width: 70px;
    font-size: 14px;
    height: 32px;
    position: relative;
    // top: 50%;
    margin-top: -16px;
    background: #075ebb;
    color: #fff;
    border-radius: 4px;
    white-space: nowrap;
}
.weui-btn_disabled.weui-btn_default {
    color: rgba(0,0,0,.3);
    background-color: #f7f7f7;
}
.content-box{
    height:80%;overflow:auto;padding-bottom:20px;background: #fff;
    .c-title{
        position: relative;
        background: #eff1f4;
        padding-top: 20px; font-weight: 600;padding:20px;
    }
    .list{
        background: #fff;padding:0 20px;
        ul{
            li{
                padding:10px 0;
                height:100px;
                border-bottom: 1px solid #ccc;
                &.no-border{
                    border-bottom:none;
                }
                .left{
                    float:left;
                    width: calc(100% - 70px);
                    height:100%;
                    position:relative;
                    display: flex;
                    .avatar{
                        display: inline-block;
                        height:100%;
                        vertical-align: middle;
                        line-height: 100px;
                        .user-img{
                            vertical-align: middle;
                            line-height: 100px;
                            width: 60px;
                            height: 60px;
                            border-radius: 50%;
                        }
                    }
                    .txt{
                        padding: 16px 0;
                        display: inline-block;
                        margin-left: 10px;
                        width: calc(100% - 100px);
                        .txt-p{
                            width:100%;
                            align-items: center;
                            vertical-align:middle;
                        }
                        .txt-area{
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            -o-text-overflow: ellipsis;
                            line-height: 20px;
                            display: block;
                            margin-bottom: 4px;
                            &:nth-child(1) {
                                font-size: 16px;
                            }
                            &:nth-child(2) span {
                                padding: 2px 10px;
                                background: #F3F3F3;
                            }
                            &:nth-child(3) span {
                                color: #999;
                            }
                        }
                    }
                }
                .right{
                    float:left;width:70px;height:100%;line-height:100px;
                }
            }
        }
    }
}
.dialog-footer{
    position: relative;bottom:0;text-align:center;width:100%;
    .btn-box{
        display: flex;
        padding: 20px;
    }
    .page-btn{
        margin: 0 auto;
        height: 30px;
        text-align: center;
        line-height: 30px;
        // border: 1px solid rgba(0, 0, 0, 0.2);
        border-radius: 4px;
        width:100px;
        float:left;
        color: #075ebb;
        border: 1px solid #075ebb;
        background-color: #ffffff;
        font-size: 14px;
        &:nth-child(2n) {
            margin-left:10px;
        }
        &.disabled{
            border: 1px solid rgba(0, 0, 0, 0.2);
            color: rgba(0, 0, 0, 0.3);
            background-color: #F7F7F7;
        }
    }
}
.cancel-btn{
    padding: 0 40px;
    /deep/.van-button{
        width: 100%;
        border-radius: 4px;
    }
}
</style>
